<template>
  <el-card shadow="never" class="main-container" style="background-color: white;">
    <template #header>添加任务</template>

    <el-input size="large" v-model.trim="state.addTaskValue"
      @keyup.enter="handleAddTask(state.addTaskValue)"
      placeholder="例如吃饭睡觉打豆豆；提示：+回车即可添加任务">
      <template #append>
        <el-button @click="handleAddTask(state.addTaskValue)">新增任务</el-button>
      </template>
    </el-input>

    <el-row style="margin-top: 15px;">
      <el-col :span="12">
        <el-text class="mx-1" type="warning">{{ state.unfinishCount }}个任务未完成</el-text>
      </el-col>
      <el-col :span="12" style="display: flex;justify-content: flex-end;">
        <el-radio-group v-model="state.status" @change="fetchTaskList()">
          <template v-for="cate in state.taskCategories">
            <el-radio-button :label="cate.value">{{ cate.label }}</el-radio-button>
          </template>
        </el-radio-group>
      </el-col>
    </el-row>

    <el-table ref="multipleTableRef" row-key="id" :data="state.tableData" :loading="state.loading" style="width: 100%"
      @sort-change="handleSortChange">
      <el-table-column property="title" label="任务计划列表">
        <template #default="{ row, $index }">
          <template v-if="row.editing">
            <el-input size="small" v-model="state.tableData[$index].title"
              style="width: 50%;min-width: 300px;margin-right: 10px;" @keyup.enter="handleEditTask(row)" />
            <el-button size="small" @click="handleCancelEdit(row)">取消</el-button>
            <el-button plain size="small" type="success" @click="handleEditTask(row)">保存</el-button>
          </template>
          <template v-else>
            <el-checkbox v-model="row.status" size="small" @change="handleChangeStatus(row)"
              style="margin-right: 10px;">
              <el-text v-if="row.status" tag="del">{{ row.title }}</el-text>
              <el-text v-else>{{ row.title }}</el-text>
            </el-checkbox>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="创建人" prop="authorName" align="center" width="120" />

      <el-table-column label="创建时间" prop="datetime" sortable align="center" width="180">
        <template #default="{ row, $index }">
          {{ $utils.formatISODateToStandard(row.datetime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="row.editing = true">修改</el-button>
          <el-popconfirm :width="delPopconfirmWidth" :title="delPopconfirmTitle(row)" @confirm="handleDelTask(row)">
            <template #reference>
              <el-button size="small" type="danger" plain>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="state.current" v-model:page-size="state.pageSize" :total="state.total"
      :layout="state.layout" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      style="margin: 15px 0 0;justify-content: center;" />
  </el-card>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const store = useStore();
const { proxy: { $axios, $utils } } = getCurrentInstance();

const multipleTableRef = ref();
const taskCategory_ALL = { value: '-1', label: '全部' };
const state = reactive({
  addTaskValue: '',
  loading: false,
  layout: 'prev, pager, next, jumper, total',
  current: 1,
  pageSize: 10,
  total: 100,
  status: taskCategory_ALL.value, // 默认全部
  unfinishCount: 0,
  tableData: [],
  taskCategories: [],
  sortField: '',
  sortValue: ''
});
const {
  delPopconfirmWidth,
  delPopconfirmTitle,
  handleEditTask,
  handleDelTask,
  handleCancelEdit,
  fetchTaskList,
  handleSizeChange,
  handleCurrentChange,
  handleChangeStatus,
  handleSortChange
} = useTaskList();

fetchTaskList();

onMounted(() => {
  const statusDef = store.getters['enums/getEnums']('task_status');
  const statusEnums = statusDef.getAllMembers();
  state.taskCategories = [taskCategory_ALL, ...statusEnums]
});

function handleAddTask(value = '') {
  const values = value.split(/\s*[,，]\s*/g);
  if (Array.isArray(values)) {
    values.forEach(val => fetchSaveTask(val));
  } else {
    fetchSaveTask(value);
  }
}

async function fetchSaveTask(title) {
  if (!title) {
    return ElMessage.warning('任务不能为空');
  }

  const datetime = $utils.formatISODateToStandard(new Date().toISOString());
  const author = store.getters['user/getUser'];
  const params = {
    title,
    datetime,
    authorId: author.id,
    author: author.username,
    authorName: author.fullname,
    status: 0
  }

  try {
    const { code, message } = await $axios.post('/api/task/add', params);
    if (code === 200) {
      state.addTaskValue = '';
      fetchTaskList();
      ElMessage.success(message);
    }
  } catch (err) {
    console.error('添加任务失败:', err);
  } finally {
    state.loading = false;
  }
}

function useTaskList() {
  const tabRef = ref();
  const popWidth = 240;
  const popTitle = ({ id, title }) => `确定删除【#${id}-${title}】这条任务吗?`;

  async function fetchTasks(page = null) {
    state.loading = true;
    const path = '/api/task/list';
    const queryParams = {
      current: page || state.current,
      pageSize: state.pageSize,
      status: state.status,
      sortField: state.sortField,
      sortValue: state.sortValue,
    }

    try {
      const {
        code,
        data: { data, current, pageSize, total, unfinishCount },
        message
      } = await $axios.get(path, queryParams);

      if (code === 200) {
        state.current = current;
        state.pageSize = pageSize;
        state.total = total;
        state.unfinishCount = unfinishCount;
        state.tableData = formatTabHandler(data);
      } else {
        ElMessage(message);
      }
    } catch (err) {
      console.error('获取任务列表失败:', err);
    } finally {
      state.loading = false;
    }
  }

  async function editTask(row) {
    if (!row.title) return ElMessage.warning('任务不能为空');

    const { datetime, status } = row;
    const params = {
      ...row,
      datetime: $utils.formatISODateToStandard(datetime),
      status: Number(status)
    };

    try {
      const { code, message } = await $axios.put(`/api/task/update/${row.id}`, params);

      if (code === 200) {
        fetchTasks();
        ElMessage.warning(message)
      }
    } catch (err) {
      console.error('任务修改失败:', err);
    }
  }

  async function delTask(row) {
    try {
      const { code, message } = await $axios.delete(`/api/task/delete/${row.id}`);
      if (code === 200) {
        fetchTasks();
        ElMessage.error(message)
      }
    } catch (err) {
      console.error('删除任务:', err);
    }
  }

  function cancelEdit(row) {
    row.editing = false;
    row.title = row.originalTitle;
  }

  function SizeCHG(val) {
    console.log(`${val} items per page`)
  }

  function CurrentCHG(val) {
    fetchTasks(val);
  }

  function formatTabHandler(data) {
    return data.map(row => ({
      ...row,
      editing: false,
      originalTitle: row.title,
      status: Boolean(row.status),
    }));
  }

  function changeStatus(row) {
    const params = {
      ...row,
      status: Number(row.status)
    }
    editTask(params);
  }

  function sortChange({ prop, order }) {
    if (!order) return false;

    const reg = /ending/g;
    state.sortField = prop;
    state.sortValue = order.replace(reg, '').toLocaleUpperCase();
    fetchTasks();
  }

  return {
    multipleTableRef: tabRef,
    delPopconfirmWidth: popWidth,
    delPopconfirmTitle: popTitle,
    fetchTaskList: fetchTasks,
    handleEditTask: editTask,
    handleDelTask: delTask,
    handleCancelEdit: cancelEdit,
    handleSizeChange: SizeCHG,
    handleCurrentChange: CurrentCHG,
    handleChangeStatus: changeStatus,
    handleSortChange: sortChange,
  };
}
</script>